package com.imddy.gkrpc.transport;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import com.imddy.gkrpc.Peer;

public class HttpTransportClient implements TransportClient {

	private String url;
	
	@Override
	public void connect(Peer peer) {
		this.url = "http://" + peer.getHost() + ":" + peer.getPort();
	}

	@Override
	public InputStream write(InputStream data) {
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			
			httpURLConnection.connect();
			IOUtils.copy(data, httpURLConnection.getOutputStream());
			
			int retCode = httpURLConnection.getResponseCode();
			if (retCode == httpURLConnection.HTTP_OK) {
				return httpURLConnection.getInputStream();
			} else {
				return httpURLConnection.getErrorStream();
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
			new IllegalStateException(e);
		}
		return null;
	}

	@Override
	public void close() {
		
	}

}
